package com.mixed.mixedserver.game.system;

import com.mixed.mixedserver.game.entity.GameMessage;
import com.mixed.mixedserver.game.network.GameNettyServer;
import com.mixed.mixedserver.game.network.GameServerHandler;
import com.mixed.mixedserver.game.state.GameStateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/game")
@CrossOrigin(origins = "*")
public class GameController {
    
    @Autowired
    private GameNettyServer gameNettyServer;
    
    @Autowired
    private GameServerHandler gameServerHandler;
    
    @Autowired
    private GameStateService gameStateService;
    
    /**
     * 获取服务器状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getServerStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("running", gameNettyServer.isRunning());
        status.put("port", gameNettyServer.getPort());
        status.put("onlinePlayerCount", gameServerHandler.getOnlinePlayerCount());
        status.put("onlinePlayers", gameServerHandler.getOnlinePlayerIds());
        status.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(status);
    }
    
    /**
     * 获取所有玩家状态
     */
    @GetMapping("/players")
    public ResponseEntity<Map<String, GameMessage.PlayerData>> getAllPlayers() {
        Map<String, GameMessage.PlayerData> players = gameStateService.getAllPlayerStates();
        return ResponseEntity.ok(players);
    }
    
    /**
     * 获取特定玩家状态
     */
    @GetMapping("/players/{playerId}")
    public ResponseEntity<GameMessage.PlayerData> getPlayer(@PathVariable String playerId) {
        GameMessage.PlayerData playerData = gameStateService.getPlayerState(playerId);
        if (playerData != null) {
            return ResponseEntity.ok(playerData);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 获取游戏统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getGameStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalPlayers", gameStateService.getOnlinePlayerCount());
        stats.put("serverUptime", System.currentTimeMillis());
        stats.put("serverRunning", gameNettyServer.isRunning());
        
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, String>> healthCheck() {
        Map<String, String> health = new HashMap<>();
        
        if (gameNettyServer.isRunning()) {
            health.put("status", "UP");
            health.put("message", "Game server is running");
            return ResponseEntity.ok(health);
        } else {
            health.put("status", "DOWN");
            health.put("message", "Game server is not running");
            return ResponseEntity.status(503).body(health);
        }
    }
    
    /**
     * 获取服务器配置信息
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getServerConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("port", gameNettyServer.getPort());
        config.put("maxPlayers", 100); // 从配置文件读取
        config.put("tickRate", 60); // 从配置文件读取
        config.put("worldBounds", Map.of(
            "width", 1000,
            "height", 1000,
            "depth", 1000
        ));
        
        return ResponseEntity.ok(config);
    }
    
    /**
     * 清理过期状态（管理接口）
     */
    @PostMapping("/cleanup")
    public ResponseEntity<Map<String, String>> cleanupStates() {
        try {
            gameStateService.cleanupExpiredStates();
            Map<String, String> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "Cleanup completed");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
}